<template>
  <div class="app-container" style="padding:8px 0px 10px 0px;height: calc(100% - 50px);">
    <el-form ref="showParamsRef" :inline="true" :model="queryParams" label-width="90px">
      <el-row style="margin-top: -10px;margin-bottom: -15px;">
        <el-form-item label="长/临:" prop="repeatIncaditor">
          <el-radio-group v-model="queryParams.repeatIncaditor" @change="handleQuery">
            <el-radio-button label="全部" value=""/>
            <template v-for="(tag, index) in dictDataMap['order_type']">
              <el-radio-button :label="tag.dictLabel" :value="tag.dictValue"/>
            </template>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="医嘱状态:" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" class="width-120"
                     placeholder="请选择" @change="handleQuery">
            <el-option label="全部" value="22"></el-option>
            <el-option v-for=" dict in dictDataMap['order_status'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医嘱内容:" prop="orderText">
          <el-input v-model="queryParams.orderText" class="width-120" placeholder="请输入医嘱内容"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="下达时间:" prop="admissionTime">
          <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                          range-separator="截止" start-placeholder="开始日期" type="daterange"
                          @change="admissionTimeChange"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button class="mb5" style="float: right" type="primary" @click="handleQuery">
            <template #icon>
              <i-ep-search/>
            </template>
            刷新
          </el-button>
          <el-button class="mb5" style="float: right" type="warning" @click="emrURL">
            <template #icon>
              <i-ep-edit/>
            </template>
            护理文书
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <el-row class="mb5">
      <el-col :span="16">
        <template v-if="configPersonIsOneTouchOrder.configValue ==='Y'">
          <el-tooltip class="box-item" content="转抄【传输】状态的医嘱，校对【长期】【临时】医嘱，并执行【临时】医嘱"
                      effect="dark" placement="bottom">
            <el-button class="ml10" type="primary" @click="executeOrder">
              <svg-icon class="mr5" icon-class="execute"/>
              转抄并执行(F1)
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="操作【医生停止】的【长期】医嘱" effect="dark" placement="bottom">
            <el-button class="ml10" type="danger" @click="stopOrder">
              <svg-icon class="mr5" icon-class="stop"/>
              转抄并停止(F8)
            </el-button>
          </el-tooltip>
        </template>
        <template v-else>
          <el-tooltip class="box-item" content="操作【传输】状态的医嘱" effect="dark" placement="bottom">
            <el-button class="ml10" type="warning" @click="orderTranscribe">
              <svg-icon class="mr5" icon-class="orderTranscribe"/>
              转抄
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="校对" effect="dark" placement="bottom">
            <el-button class="ml10" color="#7ebe47" @click="orderProofread">
              <svg-icon class="mr5" icon-class="orderProofread"/>
              校对
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="临嘱执行" effect="dark" placement="bottom">
            <el-button class="ml10" type="success" @click="executionOfImmediateOrders">
              <svg-icon class="mr5" icon-class="execute"/>
              临嘱执行
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="操作【护士执行】状态的长期医嘱" effect="dark"
                      placement="bottom">
            <el-button class="ml10" type="danger" @click="stopOrders">
              <svg-icon class="mr5" icon-class="stop"/>
              长嘱停止
            </el-button>
          </el-tooltip>
        </template>
        <el-tooltip class="box-item" content="驳回" effect="dark" placement="bottom">
          <el-button class="ml10" color="#fd7de4" @click="orderReject">
            <svg-icon class="mr5" icon-class="orderReject"/>
            驳回
          </el-button>
        </el-tooltip>
        <el-tooltip class="box-item" content="皮试结果录入" effect="dark" placement="bottom">
          <el-button class="ml10" type="warning" @click="skinEnter">
            <svg-icon class="mr5" icon-class="skin"/>
            皮试结果录入
          </el-button>
        </el-tooltip>
        <el-tooltip class="box-item" content="出院划价" effect="dark" placement="bottom">
          <el-button class="ml10" color="#067dae" @click="eighteenClick">
            <svg-icon class="mr5" icon-class="orderPricing"/>
            费用补录
          </el-button>
        </el-tooltip>
        <!--                <el-tooltip class="box-item" content="出院划价" effect="dark" placement="bottom">-->
        <!--                    <el-button class="ml10" color="#067dae" @click="orderPricing">-->
        <!--                        <svg-icon class="mr5" icon-class="orderPricing"/>-->
        <!--                        出院划价-->
        <!--                    </el-button>-->
        <!--                </el-tooltip>-->
        <el-tooltip class="box-item" content="一日清单" effect="dark" placement="bottom">
          <el-button class="ml10" color="#1e1ef0" @click="everydayDaily">
            <svg-icon class="mr5" icon-class="everydayDaily"/>
            一日清单
          </el-button>
        </el-tooltip>
        <el-tooltip class="box-item" content="打印" effect="dark" placement="bottom">
          <el-button class="ml10" type="info" @click="ordersPrint">
            <i-ep-printer/>
            打印
          </el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="8">
        <!--                <div style="float: right;margin-right: 25px">-->
        <!--                    <el-tooltip class="box-item" effect="dark" content="开检查" placement="bottom">-->
        <!--                        <el-button color="#626aef" class="ml10" @click="handleAddExam">-->
        <!--                            <svg-icon :icon-class="'exam'" class="mr5"/>-->
        <!--                            开检查(F2)-->
        <!--                        </el-button>-->
        <!--                    </el-tooltip>-->
        <!--                    <el-tooltip class="box-item" effect="dark" content="开检验" placement="bottom">-->
        <!--                        <el-button type="success" class="ml10" @click="handleAddLab">-->
        <!--                            <svg-icon :icon-class="'lab'" class="mr5"/>-->
        <!--                            开检验(F3)-->
        <!--                        </el-button>-->
        <!--                    </el-tooltip>-->
        <!--                    <el-tooltip class="box-item" effect="dark" content="开中草药" placement="bottom">-->
        <!--                        <el-button type="warning" plain class="ml10" @click="handleAddDrugChineseHerbalMedicine">-->
        <!--                            <svg-icon :icon-class="'drugChineseHerbalMedicine'" class="mr5"/>-->
        <!--                            开中草药(F4)-->
        <!--                        </el-button>-->
        <!--                    </el-tooltip>-->
        <!--                    <el-tooltip class="box-item" effect="dark" content="手术申请" placement="bottom">-->
        <!--                        <el-button type="danger" plain class="ml10" @click="handleAddOperating">-->
        <!--                            <svg-icon :icon-class="'operatingRoom'" class="mr5"/>-->
        <!--                            手术申请(F5)-->
        <!--                        </el-button>-->
        <!--                    </el-tooltip>-->
        <!--                </div>-->
      </el-col>
    </el-row>
    <el-table v-adaptive="290" :border="true" :data="form.orderList" :header-cell-style="$headerCellStyle"
              :stripe="true"
              highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column :align="'center'" type="selection" width="40"/>
      <!--                <el-table-column label="操作" :align="'center'" class-name="small-padding fixed-width" width="50"-->
      <!--                                 fixed="left">-->
      <!--                    <template #default="scope">-->
      <!--                        <el-tooltip class="box-item" v-if="scope.row.orderStatus === '1'" effect="dark" content="删除"-->
      <!--                                    placement="right">-->
      <!--                            <el-button type="danger" circle class="ml10 mb25"-->
      <!--                                       @click="handleDelete(scope.$index, scope.row)">-->
      <!--                                <template #icon>-->
      <!--                                    <i-ep-delete/>-->
      <!--                                </template>-->
      <!--                            </el-button>-->
      <!--                        </el-tooltip>-->
      <!--                    </template>-->
      <!--                </el-table-column>-->
      <el-table-column :align="'center'" fixed="left" label="医嘱状态" prop="orderStatus" width="90">
        <template #default="scope">
          <template v-for="(tag, index) in dictDataMap['order_status']">
            <template v-if="scope.row.orderStatus.includes(tag.dictValue)">
              <el-button v-if="!tag.cssClass" :class="scope.row.orderStatus === '1' ? 'mb25': ''"
                         :type="tag.listClass"
                         style="border: 1px #000000 solid">{{ tag.dictLabel }}
              </el-button>
              <el-button v-else :class="scope.row.orderStatus === '1' ? 'mb25': ''" :color="tag.cssClass"
                         style="border: 1px #000000 solid">{{ tag.dictLabel }}
              </el-button>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="是否计价" prop="billingAttr" width="90">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['billing_attr']"
                         :value="scope.row.billingAttr"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="下达时间" prop="createTime" width="140">
        <template #default="scope">
          {{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </template>
      </el-table-column>
      <el-table-column :align="'left'" fixed="left" label="医嘱类别" prop="orderClass" width="90">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['new_order_type']"
                         :value="scope.row.orderClass"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="长/临" prop="repeatIncaditor" width="60">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['order_type']"
                         :value="scope.row.repeatIncaditor"/>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :header-align="'center'" :show-overflow-tooltip="true" fixed="left"
                       label="医嘱内容"
                       prop="orderText"
                       width="200">
        <template #default="scope">
          {{ scope.row.groupNumberStyle }}<span class="ml5">{{ scope.row.orderText }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="是否医保" prop="isMedical" width="70">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']"
                         :value="scope.row.isMedical"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="途径" prop="channel" width="100">
        <template #default="scope">
          {{ scope.row.channelName }}<span v-if="scope.row.allergyResult"
                                           :style="{color: scope.row.allergyResult!= '-' ?  '#ff0000' : '#159100',fontWeight:'bold'}"
                                           class="ml5">({{
            scope.row.allergyResult
          }})</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="频次" prop="performFreq" width="100">
        <template #default="scope">
          {{ scope.row.performFreqName }}
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :header-align="'center'" :show-overflow-tooltip="true" label="执行时间"
                       prop="nursePerformTime" width="100">
        <template #default="scope">
          {{ scope.row.nursePerformTime }}
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单次用量" prop="numSingle" width="100">
        <template #default="scope">
                    <span style="margin-left: -15px"> {{ parseFloat(scope.row.numSingle).toFixed(2) }}<dict-data-tag
                      :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                      style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单次剂量" prop="singleDosage" width="100">
        <template #default="scope">
                    <span style="margin-left: -15px"> {{ parseFloat(scope.row.singleDosage).toFixed(2) }}<dict-data-tag
                      :options="dictDataMap['dose_unit']" :value="scope.row.doseUnits"
                      style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="数量" prop="sumNum" width="90">
        <template #default="scope">
                    <span style="margin-left: -15px"> {{ scope.row.sumNum }}<dict-data-tag
                      :options="dictDataMap['spec_unit']" :value="scope.row.unit"
                      style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>

      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="首日是否摆药" prop="firstDayIsDisp" width="90">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']"
                         :value="scope.row.firstDayIsDisp"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="首日摆药数量" prop="firstDayDrugDispAmount" width="100">
        <template #default="scope">
                    <span style="margin-left: -15px"> {{ scope.row.firstDayDrugDispAmount }}<dict-data-tag
                      :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                      style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="滴速" prop="dripSpeed" width="100">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_drop_speed']"
                         :value="scope.row.dripSpeed"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="执行科室" prop="implementDept" width="100">
        <template #default="scope">
          {{ scope.row.implementDeptName }}
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="医嘱说明" prop="remarks" width="120">
        <template #default="scope">
          {{ scope.row.remarks }}
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="开单医生" prop="applyUserName" width="90"/>
      <el-table-column :align="'center'" label="开单科室" prop="applyDeptName" width="90"/>
      <el-table-column :align="'center'" label="校对时间" prop="checkTime" width="140"/>
      <el-table-column :align="'center'" label="校对护士" prop="checkNurseName" width="90"/>
      <el-table-column :align="'center'" label="执行护士" prop="executeNurseName" width="90"/>
      <el-table-column :align="'center'" label="医生停止时间" prop="stopInTime" width="140"/>
      <el-table-column :align="'center'" label="护士停止时间" prop="nurseStopTime" width="140"/>
      <el-table-column :align="'center'" label="停止护士" prop="stopNurseName" width="90"/>
      <el-table-column :align="'center'" label="皮试结果" prop="skinResult" width="90"/>
      <el-table-column :align="'center'" label="签名医生" prop="doctorSignature" width="90"/>
      <el-table-column :align="'center'" label="停止摆药" prop="dispStatus" width="70"/>
    </el-table>
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :title="dialogTitle"
      :width="dialogWidth"
      @close="handleClose"
    >
      <orders-list v-if="dialogIndex ==='1'" ref="ordersListRef"/>
      <allergy-table v-if="dialogIndex ==='2'" ref="allergyTableRef" :query-params="allergyQueryParams"
                     class="allergy"/>
    </el-dialog>

  </div>

</template>

<script lang="ts" setup>
import {listOrders, updateOrderStatus} from "@/api/orders/orders.ts"
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import OrdersList from "@/views/nurse/nursePrint/ordersList.vue";
import AllergyTable from "@/views/infusion/allergyTestingConfirm/allergyTable.vue";


const {proxy} = getCurrentInstance() as any;
const currentSelectDept = proxy.$currentSelectDept
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('order_status', 'billing_attr', 'order_type', 'new_order_type',
  'sys_yes_no', 'spec_unit', 'sys_drop_speed', 'drug_classification', 'dose_unit'))


// 弹出框状态
const dialogVisible = ref<boolean>(false)
// 弹出框内容类别
const dialogType = ref<string>("")
//弹出框标题
const dialogTitle = ref<string>("")
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const queryParams = ref<any>({
  repeatIncaditor: "",
  orderStatus: "22"
})
const allergyQueryParams = ref({})
const ids = ref([]);
const configPersonIsOneTouchOrder = ref<any>({})
const selectionThis = ref<any>([]);
const ordersListRef = ref();
const allergyTableRef = ref();
const dialogIndex = ref('0');
const dialogWidth = ref("80%");
const single = ref(true);
const multiple = ref(true);
const props = defineProps({
  visitId: {
    type: String,
    default: ""
  },
  patientId: {
    type: String,
    default: "",
  },
})
const form = ref<any>({
  // 医嘱
  orderList: []
})

const emits = defineEmits(["costsSelectClick", "eighteenClick"])

// 组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('keydown',
    handleKeydown);
});
// 组件卸载时移除事件监听以避免内存泄漏
onUnmounted(() => {
  window.removeEventListener('keydown',
    handleKeydown);
});

function handleKeydown(event) {
  if (event.keyCode == "112") {
    // F1 转抄并执行
    //阻止浏览器默认事件
    event.preventDefault();
    executeOrder()
  } else if (event.keyCode == "113") {
    // F2 开检查
    //阻止浏览器默认事件
    event.preventDefault();
  } else if (event.keyCode == "114") {
    // F3 开检验
    //阻止浏览器默认事件
    event.preventDefault();
  } else if (event.keyCode == "115") {
    // F4 开中草药
    //阻止浏览器默认事件
    event.preventDefault();
  } else if (event.keyCode == "116") {
    // F6 手术申请
    //阻止浏览器默认事件
    event.preventDefault();
  }
}

function admissionTimeChange(e) {
  if (e) {
    dateRange.value = [proxy.$parseTime(e[0], "{y}-{m}-{d} 00:00:00"), proxy.$parseTime(e[1], "{y}-{m}-{d} 23:59:59")]
  }
  getList()
}

/**
 * 转抄
 */
function orderTranscribe() {
  initSelectionThis("", "2")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【传输】状态的医嘱，请勾选状态为【传输】的医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【转抄】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "3"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("转抄成功")
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 转抄并执行
 */
function executeOrder() {
  initSelectionThis("", "2")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【传输】状态的医嘱，请勾选状态为【传输】的医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【转抄并执行】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "47"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("转抄并执行成功")
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 转抄并停止
 */
function stopOrder() {
  initSelectionThis("0", "9")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【医生停止】状态的【长期】医嘱，请勾选医嘱状态为【医生停止】的【长期】医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【转抄并停止】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "35"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("转抄并停止成功")
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 校对
 */
function orderProofread() {
  initSelectionThis("", "3")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【转抄】状态的医嘱，请勾选状态为【转抄】的医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【校对】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "7"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("校对成功")
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 临嘱执行
 */
function executionOfImmediateOrders() {
  initSelectionThis("1", "7")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【校对】状态的【临时】医嘱，请勾选状态为【校对】状态的【临时】医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【临嘱执行】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "4"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("临嘱执行成功")
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 长嘱停止
 */
function stopOrders() {
  initSelectionThis("0", "9")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【校对】状态的长期医嘱，请勾选状态为【校对】状态的长期医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【长嘱停止】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "5"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("长嘱停止成功")
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 驳回
 */
function orderReject() {
  initSelectionThis("", "2")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【传输】状态的医嘱，请勾选状态为【传输】状态的医嘱后操作。")
  }
  ElMessageBox.prompt('驳回说明', '确认要进行【驳回】吗', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\S+$/,
    inputErrorMessage: '驳回理由不能为空',
  })
    .then(({value}) => {
      const data = {
        ids: ids.value,
        statusType: "8",
        rebuteRemarks: value
      }
      updateOrderStatus(data).then(() => {
        ElMessage.success("驳回成功")
        getList()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Input canceled',
      })
    })
}

/**
 * 皮试结果录入
 */
function skinEnter() {
  dialogWidth.value = '88%'
  dialogIndex.value = '2'
  dialogVisible.value = true
  dialogTitle.value = "皮试结果录入"
  allergyQueryParams.value = {
    visitIdOrClinicId: props.visitId
  }
  nextTick(() => {
    allergyTableRef.value.getList();
  })
}


/**
 * 组织多选功能 向后台传递的ids
 * @param repeatIncaditor 长期/临时
 * @param type 医嘱状态
 */
function initSelectionThis(repeatIncaditor: string, type: string) {
  let thisList = [] as any
  thisList = selectionThis.value.filter((item: any) => item.orderStatus === type)
  // type = 07（校对状态的长期医嘱）
  if (repeatIncaditor + type === '07') {
    thisList = thisList.filter((item: any) => item.repeatIncaditor === '0')
  }
  // type = 17（校对状态的临时医嘱） （获取状态为校对的临时医嘱）
  if (repeatIncaditor + type === '17') {
    thisList = thisList.filter((item: any) => item.repeatIncaditor === '1')
  }
  // type = 09 （获取状态为医生停止的长期医嘱）
  if (repeatIncaditor + type === '09') {
    thisList = thisList.filter((item: any) => item.repeatIncaditor === '0')
  }
  ids.value = thisList.map((item: any) => item.id);
}


/**
 * dialog关闭事件
 */
function handleClose() {
  dialogType.value = ""
  dialogVisible.value = false
  if (dialogIndex.value === '2') {
    handleQuery()
  }
}


// 多选框选中数据
function handleSelectionChange(selection) {
  selectionThis.value = selection
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


function handleQuery() {
  getList()
}

function getList() {
  const param = {
    orgId: userInfo.orgId,
    visitId: props.visitId,
    orderText: queryParams.value.orderText,
    repeatIncaditor: queryParams.value.repeatIncaditor,
    orderStatus: queryParams.value.orderStatus === '22' ? '' : queryParams.value.orderStatus,
    orderStatusNotInArray: ['1']
  }
  listOrders(proxy.$addDateRange(param, dateRange.value)).then((res: resType) => {
    let unsave = form.value.orderList.filter(e => e.id == null)
    form.value.orderList = []
    const data: any = res.data
    data.forEach((item: any, index) => {
      item.itemId = ""
      if (item.orderStatus != "1") {
        // 除了新开以外的
        item.isShow = false
      } else {
        item.isShow = true
      }
      item.doseUnitsName = dictStore.getMateDictInfo(dictDataMap.value['dose_unit'], item.doseUnits).dictLabel
      const unit = item.packSize === "1" ? item.minUnits : item.packageUnits
      item.unit = unit
      item.unitsName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
      item.minUnitsName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], item.minUnits).dictLabel
      item.orderClassDisabled = item.orderClass === '4' || item.orderClass === '5'
      let price: number = 0;
      if (item.ordersCostVoList != null) {
        item.ordersCostVoList.forEach(orderCost => {
          price += Number(orderCost.price)
        })
      }
      item.price = price
      form.value.orderList.push(item)
      selectionThis.value = []
    })
    form.value.orderList = form.value.orderList.concat(unsave)
    unsave = []
  })
}

/**
 * 个人参数 是否一键执行医嘱
 */
function getConfigPersonIsOneTouchOrder() {
  let configPersonIndex = useUserStore.user.configPersonList.findIndex((configPerson: any) => {
    return configPerson.configKey === "is_one_touch_order"
  })
  if (configPersonIndex > -1) {
    configPersonIsOneTouchOrder.value = useUserStore.user.configPersonList[configPersonIndex]
  }
}

/**
 * 一日清单
 */
function everydayDaily() {
  emits("costsSelectClick", "一日清单")
}

/**
 * 费用录入
 */
function eighteenClick() {
  emits("eighteenClick")
}

//电子病历单点登录
function emrURL() {
  const emrURL = 'http://123.139.118.82:9000' //临时写法
  //链接跳转
  let url = `${emrURL}/emrcloud/showRecord/transfer?from=his&name=InpNurseEditor&orgId=${userInfo.orgId}&patientRegId=${props.visitId}&userId=${userInfo.userId}&currentDeptAreaId=${currentSelectDept}&p1=his&p2=his`
  window.open(url, "_blank")
}

/**
 * 医嘱打印
 */
function ordersPrint() {
  dialogWidth.value = '60%'
  dialogIndex.value = '1'
  dialogVisible.value = true
  dialogTitle.value = "医嘱打印"
  nextTick(() => {
    ordersListRef.value.initVisitOrderPrint(false, props.visitId);
  })
}

getConfigPersonIsOneTouchOrder()
getList()

defineExpose({
  getList
})
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.el-input__wrapper .el-input__inner) {
  margin-right: -15px;
}

:deep(.el-form-item__content) {
  margin-bottom: 6px;
}

:deep(.el-form-item__error) {
  font-size: 11px;
  color: #ff0000;
}

:deep(.el-button--small) {
  --el-button-size: 20px;
}

:deep(.el-table__body tr.current-row>td>div>button>span ) {
  color: #000000 !important;
}

:deep(.allergy .el-table--small) {
  height: 600px !important;
}

</style>
